<template>
  <div class="question">
    <el-card style="width:98%;margin:30px auto;">
      <div clas="title" style="font-weight:bold;font-size:17px">题库
      <span style="font-size: 1px;float: right;cursor: pointer "   @click="downloadTemplate">点击下载xlsx模板</span>
      </div>
      <div style="display: flex;justify-content: space-between">
        <!--插入和批量删除-->

        <div style="margin: 20px 2px">
          <el-button type="primary" icon="el-icon-plus" circle @click="addOpen" title="添加"></el-button>
          <el-button type="danger" @click="delBatch" icon="el-icon-delete" title="批量删除" slot="reference"
                     style="margin-left: 10px"></el-button>

            <el-upload style="display: inline-block;margin-left: 10px"
              :action="'http://' + serverIp +':8880/question/import'"
                       :on-success="handlerSuccess"
                       accept=".xlsx"
             :show-file-list="false">
              <el-button size="small" type="primary">导入</el-button>
            </el-upload>



          <el-button type="primary" style="margin-left: 10px" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button>

        </div>
        <!--模糊查询-->
        <div style="margin: 20px 5px">
          <el-select v-model.trim="type" placeholder="请选择试卷类型">
            <el-option label="选择题" value="1"></el-option>
            <el-option label="判断题" value="2"></el-option>
            <el-option label="简答题" value="3"></el-option>
          </el-select>

          <el-select v-model="courseId" placeholder="请选择课程" style="margin-left: 10px">
            <el-option v-for="item in courses" :label="item.name" :value="item.id" :key="item.id"></el-option>

          </el-select>

          <el-button class="ml-5" type="primary" style="margin-left: 10px" @click="load">搜索</el-button>
          <el-button type="warning" @click="reset">重置</el-button>
        </div>


      </div>
      <!--表格渲染-->
      <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="题目名称"
          align="center"
          :formatter="stateFormat"
        >
        </el-table-column>

        <el-table-column
          prop="courseName"
          label="所属课程"
          align="center"
          :formatter="stateFormat"
        >

          <template v-slot="scope">
<!--            <span>{{courses.find(v=>v.id==scope.row.courseId).name}}</span>-->
            <div v-for="item in courses ">
              <span v-if="scope.row.courseId==item.id">{{item.name}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="题目类型">

          <template slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.type === 1">选择题</el-tag>
            <el-tag type="warning" v-if="scope.row.type === 2">判断题</el-tag>
            <el-tag type="success" v-if="scope.row.type === 3">简答题</el-tag>

          </template>

        </el-table-column>
        <el-table-column prop="a" label="选项a" :formatter="stateFormat"></el-table-column>
        <el-table-column prop="b" label="选项b" :formatter="stateFormat"></el-table-column>
        <el-table-column prop="c" label="选项c" :formatter="stateFormat"></el-table-column>
        <el-table-column prop="d" label="选项d" :formatter="stateFormat"></el-table-column>
        <el-table-column prop="score" label="分数" width="80" align="center"></el-table-column>
        <!--        <el-table-column prop="userId" label="创建人id" width="80" align="center"></el-table-column>-->
        <el-table-column prop="time" label="创建时间" align="center" :formatter="dateFormat"></el-table-column>
        <el-table-column prop="answer" label="答案" width="80" align="center" :formatter="stateFormat"></el-table-column>
        <el-table-column prop="detail" label="解析" width="80" align="center" :formatter="stateFormat">
        </el-table-column>


        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="info" icon="el-icon-message" @click="look(scope.row)" circle title="详细信息"></el-button>

            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" circle></el-button>

            <el-button @click="del(scope.row.id)" title="删除"
                       slot="reference" type="danger" icon="el-icon-delete" circle
                       style="margin-left: 10px"></el-button>

          </template>
        </el-table-column>
      </el-table>


      <!--分页-->
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <!--弹窗-->
    <el-dialog title="试卷信息" :visible.sync="addDialogVisible"  :destroy-on-close="true">
      <el-form label-width="80px" size="small" ref="form" :rules="rules" :model="form">
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程">
            <el-option v-for="item in courses" :label="item.name" :value="item.id" :key="item.id"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择题目类型">
            <el-option label="选择题" value=1 key="选择题"></el-option>
            <el-option label="判断题" value=2 key="判断题"></el-option>
            <el-option label="简答题" value=3 key="简答题"></el-option>
          </el-select>
        </el-form-item>

        <div v-if="form.type== 1">
          <el-form-item label="a选项">
            <el-input v-model="form.a" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="b选项">
            <el-input v-model="form.b" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="c选项">
            <el-input v-model="form.c" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="d选项">
            <el-input v-model="form.d" autocomplete="off"></el-input>
          </el-form-item>
        </div>


        <el-form-item label="分数" prop="score">
          <el-select v-model="form.score" placeholder="请选择分值" filterable>
            <el-option
              v-for="item in 100"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="答案" v-if="form.type==1">
          <el-radio v-model="form.answer" label="A">A</el-radio>
          <el-radio v-model="form.answer" label="B">B</el-radio>
          <el-radio v-model="form.answer" label="C">C</el-radio>
          <el-radio v-model="form.answer" label="D">D</el-radio>
        </el-form-item>

        <el-form-item label="答案" v-if="form.type==2">
          <el-radio v-model="form.answer" label="是">是</el-radio>
          <el-radio v-model="form.answer" label="否">否</el-radio>
        </el-form-item>
        <el-form-item label="答案" v-if="form.type==3">
          <el-input type="textarea" v-model="form.answer" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="解析" prop="detail">
          <el-input type="textarea" :rows="5" maxlength="150"
                    placeholder="一次最多输入150个，多个换行输入"
                    v-model="form.detail" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!--查看弹窗-->

    <el-dialog title="详细信息" :visible.sync="lookDialogVisible" :destroy-on-close="true">
      <el-form label-width="80px" size="small" ref="form" :model="form">

        <el-form-item label="名称:">
          {{ form.name }}
        </el-form-item>
        <el-form-item label="题目类型:">

          <el-tag type="primary" v-if="form.type === 1">选择题</el-tag>
          <el-tag type="primary" v-if="form.type === 2">判断题</el-tag>
          <el-tag type="warning" v-if="form.type === 3">简答题</el-tag>

        </el-form-item>
        <div v-if="form.type ==1">
          <el-form-item label="选项a:">
            <el-input type="text" v-model="form.a" disabled/>
          </el-form-item>
          <el-form-item label="选项b:">
            <el-input type="text" v-model="form.b" disabled/>
          </el-form-item>
          <el-form-item label="选项c:">
            <el-input type="text" v-model="form.c" disabled/>
          </el-form-item>
          <el-form-item label="选项d:">
            <el-input type="text" v-model="form.d" disabled/>
          </el-form-item>

        </div>
        <el-form-item label="分值:">
          {{ form.score }}
        </el-form-item>
        <el-form-item label="创建时间:">
          {{ form.time }}
        </el-form-item>
        <el-form-item label="创建人id:">
          {{ form.userId }}
        </el-form-item>
        <el-form-item label="答案:">
          {{ form.answer }}
        </el-form-item>
        <el-form-item label="解析:">
          {{ form.detail }}
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {serverIp} from '../../../public/config';

export default {
  name: "Index",

  data() {
    return {
      courses:[],
      loading: true,

      dialogVisible1: false,
      rules: {
        name: [
          {required: true, message: '请填写名称', trigger: 'blur'},
          // {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择类型', trigger: 'blur'},
        ],
        answer: [
          {required: true, message: '请填写答案', trigger: 'blur'},

        ], score: [
          {required: true, message: '请选择分值', trigger: 'blur'},

        ],
      },
      courseId:'',
      form: {},
      addDialogVisible: false,
      serverIp: serverIp,
      type: '',
      tableData: [],
      multipleSelection: [],
      pageNum: 1,
      pageSize: 5,
      total: 0,
      roles: [],
      lookDialogVisible: false

    }
  },
  watch: {
    form: {
      handler(newVal, oldVal) { // 固定触发此函数
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.load()
    this.request.get("/role").then(res => {
      this.roles = res.data
    })

    this.request.get("/course/findAll").then(res => {
      this.courses = res.data
    })

  },
  methods: {
    downloadTemplate(){
      this.$confirm('是否要下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'msgbox',
      }).then(() => {
        window.open(`http://${serverIp}:8880/question/downloadTemplate`)

        this.$message({
          type: 'success',
          message: '下载成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下载'
        });
      });
    },

    //导入
    handlerSuccess(){
      this.$message({
        type: 'success',
        message: '导入成功!'
      });
      this.load()
    },

    exp() {
      this.$confirm('是否要导出excel, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'msgbox',
      }).then(() => {
        window.open(`http://${serverIp}:8880/question/export`)

        this.$message({
          type: 'success',
          message: '导出成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        });
      });
    },

    // 格式化表格消息内容
    stateFormat(row, column, cellValue) {
      if (!cellValue) return "";
      if (cellValue.length > 6) {
        //最长固定显示5个字符
        return cellValue.slice(0, 6) + "...";
      }
      return cellValue;
    },
    dateFormat(row, column, cellValue, index) {
      const daterc = row[column.property]
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + "-" + hours + ":" + minutes + ":" + seconds;
      }
    },


    //新增
    save() {

      this.$refs['form'].validate((valid) => {
        if (valid) {  // 表单校验合法
          this.request.post("/question/saveQuestion", this.form).then(res => {
            if (res.code === 200) {
              this.$message.success("保存成功")
              this.addDialogVisible = false
              this.load()
            } else {
              this.$message.error("保存失败")
            }
          })
        }
      })

    },
    resetForm() {
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      })

      this.addDialogVisible = false

    },
    //添加弹窗
    addOpen() {
      this.addDialogVisible = true
      this.form = {}
    },


//编辑弹窗
    edit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.addDialogVisible = true
    },

    //详细消息弹窗
    look(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.lookDialogVisible = true
    },


    //初始化分页
    load() {
      this.request.get("/question/findPage", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          courseId:this.courseId,
          type: this.type,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total

      })
    },


    //根据id进行删除
    del(id) {
      this.$confirm('你确定要删除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'msgbox',
      }).then(async () => {
        this.request.delete("/question/del/" + id).then(res => {
          if (res.code === 200) {
            this.$message({message: '删除成功', type: "success"})
            this.load()
          } else {
            this.$message({message: '删除失败', type: "error"})
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'success'
        })
      })
    },

    //多选框
    handleSelectionChange(val) {
      this.multipleSelection = val

    },

    //批量删除
    delBatch() {
      this.$confirm('你确定要批量删除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'msgbox',
      }).then(async () => {


        let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
        if(ids.length ==0){
          this.$message.warning("请选择要删除的数据")
          return
        }
        this.request.post("/question/del/batch", ids).then(res => {
          if (ids.length === 0) {
            this.$message({
              type: 'warning',
              message: '请选择数据!'
            });
            return
          }

          if (res.code === 200) {
            this.$message({message: '批量删除成功', type: "success"})
            this.load()
          } else {
            this.$message({message: '批量删除失败', type: "error"})
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'success'
        })
      })
    },


    //重置
    reset() {
      this.type = ''
      this.courseId = ''
      this.load()
    },

    //当前页面的个数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },

    //当前页面从哪里开始
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },


  }
}
</script>

<style lang="scss" scope>

.question{
  .el-dialog {
    width: 40%;
  }


  @media screen and (max-width: 440px) {
    .el-dialog {
      width: 90%;
    }

    @media only screen and (min-width:600px) and (max-width:1200px){
      .el-dialog {
        width: 60%;
      }
    }

    @media only screen and (min-width:441px) and (max-width:599px){
      .el-dialog {
        width: 80%;
      }
    }
  }
}


</style>
<style >

@media (max-width: 720px) {
  .msgbox{
    width: 327px !important;
  }
}

</style>
